package com.senior.sendmessage.xxl;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import cn.hutool.core.util.ObjectUtil;
import com.senior.sendmessage.entity.CityListDTO;
import com.senior.sendmessage.service.WeatherService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author Baijl
 * @version 0.0.1
 * @date 2021-12-12 15:40
 * @description TODO
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WeatherScheduleJob {
    private final static FIFOCache<String, CityListDTO> FIFO_CACHE = CacheUtil.newFIFOCache(1);
    private final String KEY = "weather";
    private final WeatherService weatherService;


    /**
     * 设置城市列表缓存
     */
    @XxlJob(value = "setCityListHandler", init = "init", destroy = "destroy")
    public synchronized void setCityList() {
        final CityListDTO list = weatherService.queryWeatherList();
        FIFO_CACHE.put(KEY, list);
        if (ObjectUtil.isNotEmpty(list.getResult())) {
            log.info("定时查询城市列表！共{}条", list.getResult().size());
        } else {
            log.info("查询城市列表超过上限！");
        }
    }

    public void init() {
        log.info("init");
    }

    public void destroy() {
        log.info("destroy");
    }

    /**
     * 获取城市列表缓存
     *
     * @return {@link CityListDTO}
     */
    public synchronized CityListDTO getCityList() {
        return FIFO_CACHE.get(KEY);
    }

}
